//
//  YDateUtil.swift
//  friends
//
//  Created by xwh on 2021/4/8.
//

import UIKit

struct YDateUtil {
     
    //get time now 2021 - 10 - 11
    //format = "yyyy-MM-dd HH:mm:ss"
    public static func getDateNow(format:String)->String{
        let df = DateFormatter()
        df.dateFormat = format
        df.locale = Locale.current
        return df.string(from: Date())
    }
    
    //get date with "yyyy-MM-dd HH:mm:ss"
    public static func getDate(time:String,format:String)->Date?{
        let df = DateFormatter()
        df.dateFormat = format
        df.locale = Locale.current
        return df.date(from: time)
    }
    
//    get date components [.month]
    public static func getComponent(date:Date,timeCom:Set<Calendar.Component>)->DateComponents{
        let calendar = Calendar.current
        return calendar.dateComponents(timeCom, from: date)
    }
    
    //get days in month
    public static func days(year:Int,month:Int)->Int{
        
        var com = DateComponents()
        com.year = year
        com.month = month
        com.day = 1
        
        let calendar = Calendar.current
        
        if let date:Date = calendar.date(from: com) {
            
            let days = calendar.range(of: .day, in: .month, for: date)
            return days?.count ?? 0
        }
        
        return 0
     
    }
    
    //create date
    public static func createDate(year:Int,month:Int,day:Int)->Date?{
        
        var com = DateComponents()
        com.year = year
        com.month = month
        com.day = day
        
        let calendar = Calendar.current
        
        return calendar.date(from: com)
        
    }
    
    public static func getAge(start:Date)->Int{
        
        //now
//        let now = YDateUtil.getDateNow(format: "yyyy-MM-dd")
//
//        if let nowDate:Date = YDateUtil.getDate(time: now, format: "yyyy-MM-dd") {
//
//            let com = YDateUtil.getComponent(date: nowDate, timeCom: [.year,.month,.day])
//            let com2 = YDateUtil.getComponent(date: start, timeCom: [.year,.month,.day])
//
//            let years:Int = ((com.year ?? 0) - (com2.year ?? 0))
//
//            if (com.month ?? 0) > (com2.month ?? 0) {
//                    return years + 1
//            }
//        }
        
        let timeinterval:TimeInterval = start.timeIntervalSinceNow
        return -(Int)(trunc(timeinterval/(60*60*24)) / 365)
    }
    
    
    
    
    
}
